package com.boful.convert.core.impl.utils;

import java.io.File;
import java.io.IOException;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.Operation;

/**
 * 图片缩放、压缩
 * 
 * @author ligson
 * 
 */
public class ImageMagickUtils {
	private static ConvertCmd cmd = new ConvertCmd();

	/**
	 * 图片resize
	 * 
	 * @param src
	 * @param dest
	 * @param width
	 *            -1 自适应
	 * @param height
	 *            -1 自适应
	 * @param imageMagickBaseHome
	 * @throws Exception
	 */
	public static void resize(File src, File dest, int width, int height,
			String imageMagickBaseHome) throws Exception {
		if (imageMagickBaseHome != null) {
			ConvertCmd.setGlobalSearchPath(imageMagickBaseHome);
		}
		
		//截图后压缩一下
		compress(src, dest, imageMagickBaseHome);
		
		IMOperation op = new IMOperation();
		op.addImage(src.getAbsolutePath());
		if (width > 0 && height > 0) {
			op.resize(width, height, "!");
		} else {
			op.resize(width, height);
		}

		op.addImage(dest.getAbsolutePath());
		cmd.run(op);
		

	}

	/***
	 * 图片压缩接口
	 * 
	 * @param src
	 *            源文件
	 * @param dest
	 *            目标文件
	 * @param imageMagickBaseHome
	 *            convert搜索路径
	 * @throws Exception
	 *             压缩失败
	 */
	public static void compress(File src, File dest, String imageMagickBaseHome)
			throws Exception {
		// 压缩质量设置
		final String QUALITY = "75%";
		if (imageMagickBaseHome != null) {
			ConvertCmd.setGlobalSearchPath(imageMagickBaseHome);
		}
		IMOperation op = new IMOperation();
		op.addImage(src.getAbsolutePath());
		op.addRawArgs("-quality", QUALITY);

		op.addImage(dest.getAbsolutePath());
		cmd.run(op);
		
		
	}

	public static void main(String[] args) {
		try {
			File src = new File("F:/pic/demo.gif");
			File dest = new File("F:/pic/demo3.gif");
			resize(src, dest, 100, 50, "C:/ProgramFiles/ImageMagick-6.9.0-Q8/");
			//compress(src, dest, "C:/ProgramFiles/ImageMagick-6.9.0-Q8/");
			System.out.println(dest.exists());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
